<?php
function saveToExcel($filename,$title,$info,$data){
	import('@.Excel.PHPExcel');

	$objPHPExcel = new PHPExcel();

	//文件详细信息
	$objPHPExcel->getProperties()->setCreator("yidie") //创建人
	->setLastModifiedBy("yidie")  //最后修改人
	->setTitle($title)	//标题
	->setSubject($title)	//主题
	->setDescription($info)//备注
	->setKeywords("yidie") //标记
	->setCategory("网页导出");	//类别

	//插入数据
	$objPHPExcel->setActiveSheetIndex(0);  //激活第一页

	$baserow = 1;

	$col=0;
	$row=0;

	$colCount=0;
	$vn="";
	
	if($data){
			
		$fname =$data[0];
		foreach($fname as $k=>$v){
			//从sql自定义列名需要转码
			$vn = mb_convert_encoding($k, "UTF-8", "GB2312");
  			$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($col,$baserow,$vn);
			$col++;
		}
		$colCount = $col;
		$baserow++;

		foreach($data as $k=>$v){
			$col=0;
			foreach($v as $vk=>$vv){
				$vn = mb_convert_encoding($vk, "UTF-8", "GB2312");
				if(strstr($vn,'date') or strstr($vn,'时间') or strstr($vn,'time')){
					$d = (array)$vv;
					$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($col,$baserow+$row,$d['date']);
				}else if(strstr($vn,'qty') or strstr($vn,'数') or strstr($vn,'amount') or strstr($vn,'金额') or strstr($vn,'元')){
					$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col,$baserow+$row,$vv);
				}else{
					$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($col,$baserow+$row,$vv);
				}
				$col++;
			}
			$row++;
		}

		for($i=0;$i<$colCount; $i++){
			//列宽自适应
			$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn($i)->setAutoSize(true);			
		}
	}
		
	//命名工作表
	$objPHPExcel->getActiveSheet()->setTitle($title);

	//激活首页,表格打开时显示该页
	$objPHPExcel->setActiveSheetIndex(0);


	// Save Excel 2007 file

	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

	$stamp = '/Public/download/'.$filename.'.xlsx';
	$path = getcwd().$stamp;

	if(file_exists($path)){
		unlink($path);
	}

	$objWriter->save($path);

	$url = "http://".$_SERVER['HTTP_HOST'].'/DOC'.$stamp ;
	//header('Location:'.$url);

	return $url;
}
